package zhu.areas.hatchnav.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.opensymphony.xwork2.inject.util.FinalizablePhantomReference;

import zhu.areas.hatchnav.data.Article;
import zhu.common.dao.BaseDAOImpl;
import zhu.common.data.Pager;
import zhu.common.utils.IPagerManager;

public class ArticleDAOImpl extends BaseDAOImpl implements IArticleDAO {
	private IPagerManager pagerManager;

	public Pager findArticlesByTypeId(Integer articleTypeId, Integer pageSize,
			String currentPage, String pageMethod) {
		// TODO Auto-generated method stub
		String hsql = " from Article where artType = '" + articleTypeId
				+ "' order by pubTime desc";
		return this.pagerManager.getPager(hsql, pageSize, currentPage,
				pageMethod);
	}

	//修改文章访问量
	public void incArticleVisitNum(Integer articleID) {
		// TODO Auto-generated method stub
		Article article = (Article) this.findById(Article.class, articleID);
		article.setVisitNum(article.getVisitNum() + 1);
		this.update(article);
	}

	// 按照访问量查找前topCount名的文章列表
	public List<Article> findTopArticlesByVisitNum(final Integer topCount) {

		return  (List<Article>)getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						String hql = " from Article order by visitNum desc";
						Query query = session.createQuery(hql);
						query.setMaxResults(topCount);
						return query.list();
					}
				});
	}

	//根据文章类型查找top文章
	public List<Article> findTopArticlesByTypeID(Integer articleTypeID, Integer topCount) {
		return this.findTopArticlesByProperty("artType", articleTypeID.toString(), topCount);
	}
	
	//根据文章主题查找top文章
	public List<Article> findTopArticlesByTopicID(Integer articleTopicID, Integer topCount) {
		return this.findTopArticlesByProperty("articleTopic", articleTopicID.toString(), topCount);
	}
	
	
	
	//根据属性名查找top文章
	private List<Article> findTopArticlesByProperty(final String propertyName, final String propertyValue, final Integer topCount) {
		return  (List<Article>)getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						String hql = " from Article where " + propertyName+ " = '" + propertyValue + "' order by visitNum desc";
						Query query = session.createQuery(hql);
						query.setMaxResults(topCount);
						return query.list();
					}
				});
	}
	
	public IPagerManager getPagerManager() {
		return pagerManager;
	}

	public void setPagerManager(IPagerManager pagerManager) {
		this.pagerManager = pagerManager;
	}
}
